#-------------------------------------------------------------------------------
# Name: CheckTDDSyntax
# Checks the syntax of the TDD file
# Author: rawat
#
# Created: 22-02-2011 Copyright: (c) rawat 2011 Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python


import sys
import uuid
import TestCase

class CheckTDDSyntax(object):
	"""
	   Checks the syntax of the TDD file.
	   1. Names should not have spaces
	   2. DataType should be of given types - case sensitive
	   3. Facets should be of given types - case sensitive
	   4. Param should have data[] list size == 4.
	"""

	def __init__(self, attribs):
		self.Attributes = attribs
		#print "Number of attributes", len(self.Attributes)
		self.names = []
		self.types = []
		self.facets = []
		self.data = []
		self.refTypes = ["","int", "bool", "double", "string", "object", \
					"param_real", "param_length", "param_angle",	"param_string", "param_boolean", \
					"List<int>", "List<bool>", "List<double>", "List<string>",
					"List<object>",]
		self.refFacets = ["sp_IN", "sp_OUT", "sp_NEUTRAL"]
		for att in self.Attributes :
			name = att["name"]
			self.types.append(att["type"])
			self.names.append(att["name"])
			#self.facets.append(att["facet"])
			self.data.append(att["data"])
			#print att
		#print "Types : ", self.types
		#print "Facets : ", self.facets

		return

	def CheckNames(self):
		""" Checks the name of the attribute """
		for att in self.Attributes :
			name = att["name"]
			if self.names.count(name) > 1 :
			   sys.stderr.write( "\nDuplicate attribute found " + name )
			   return -101
			if -1 != name.find(" ") :
			   sys.stderr.write("\nAttribute :" + name + " has space. Spaces are not allowed in attribute name. " )
			   return -102
			if len(name)  < 1:
			   sys.stderr.write( "\nEmpty Attribute " )
			   return -103
		#print names, len(names)
		return 0


	def CheckTypes(self):
		""" Checks the data type of the attribute """

		for i, typ in enumerate(self.types) :
			if self.refTypes.count(typ) < 1 :
			   sys.stderr.write( "\nAttribute : " + self.names[i] + ". Invalid type found : " +  typ)
			   sys.stderr.write( "\n\tType should be one of "+ str( self.refTypes))
			   return -201
		return 0

	def CheckFacet(self):
		""" Checks the facet of the attribute """

		for i, fac in enumerate(self.facets) :
			if self.refFacets.count(fac) < 1 :
			   sys.stderr.write("\nAttribute : " + self.names[i] + ". Invalid facet found " + str(fac) )
			   sys.stderr.write("\n\tFacet should be one of " + str(self.refFacets) )
			   return -301
		return 0

	def CheckParamAttr(self):
		""" Checks if the param attr have data of size four """

		for i in range( len(self.types)):
			if False == self.types[i].startswith("param") :
			   continue

			if len(self.data[i]) != 4 :
			   sys.stderr.write("\nAttr " + self.names[i] + " data is only " + str(self.data[i]) )
			   sys.stderr.write("\n\tparam attr should have Data list of four elements " )
			   return -401

			if self.Attributes[i]["UI"] != "Param" :
			   sys.stderr.write("\nAttr " + self.names[i] + " UI is invalid : " + str(self.Attributes[i]["UI"]) )
			   sys.stderr.write("\n\tUI should be of type Param or empty string. " )
			   return -402

		return 0

	def Check(self):
		assert(self.CheckNames() == 0)
		#assert(self.CheckFacet() == 0)
		assert(self.CheckTypes() == 0)
		#assert(self.CheckParamAttr() == 0)
		return 0

def ProjectUUID(attr) :

	retVal = "\nsolutionUuid = \""  + str(uuid.uuid4()).upper() + "\""
	retVal += "\nmodelerProjectUuid = \""  + str(uuid.uuid4()).upper() + "\""
	retVal += "\nuiProjectUuid = \""  + str(uuid.uuid4()).upper() + "\""

	return retVal

def Box(key, value, end = ",") :

	retVal = "\"" + key + "\" : \"" + value + "\""
	if len(end) :
		retVal += end
	return retVal

def AddAttributesUI(name, ui, attData, x, y, length, width, end = ",") :

	data = "\"data\" : ["
	for d in attData :
		if type(d).__name__ == "int" :
			data += str(d) + ","
		else :
			data += "\"" + d + "\", "
	data += "],"
	retval = "\n{" + Box("name", name) + Box("UI", ui) + data + Box("x", str(x)) + Box("y", str(y)) + Box("length", str(length)) + Box("width", str(width), "},")
	return retval

# AttributesUI=[
# "name":"${attr.name}", "UI":"${attr.UI}", "data":["OpenFileDialog"], "x":"0", "y":"0", "length":"0", "width":"0", "style":"CATDlgGridLayout" },
# ]

def AttributesUI(Attributes) :

	retval = "\nAttributesUI=["
	x = 100
	y = 10
	for att in Attributes :
		if len(att["UI"]) < 1 :
			continue
		elif att["UI"] != "RadioButton" and att["UI"] != "CheckBox" and att["UI"] != "Button" and att["UI"] != "LinkLabel":
			retval += AddAttributesUI( att["name"], "Label", att["data"], 10, y, 80, 20)
			x = 100
		else :
			x = 10
		retval += "\n{"
		retval += Box("name" , att["name"] )
		retval += Box("UI" , att["UI"] )
		data = "["
		for d in att["data"] :
			if type(d).__name__ == "int" :
				data += str(d) + ","
			else :
				data += "\"" + d + "\", "
		data += "]"
		retval += "\"data\" : " + data + ","
		retval += Box("x" , str(x) )
		retval += Box("y" , str(y) )
		retval += Box("length" , "150" )
		if att["UI"] == "ListView" :
			retval += Box("width" , "100", "" )
			y += 80
		elif att["UI"] == "MonthCalendar" :
			y += 130 # MonthCalendar length is fixed to 162
			retval += Box("width" , "150", "" )
		else :
			retval += Box("width" , "20", "" )
		retval += "},"
		y += 30
		if att["UI"] == "Button" and len(att["data"]) > 0 and att["data"][0] == "OpenFileDialog" :
			retval += AddAttributesUI( att["name"], "OpenFileDialog", att["data"], x, y, 100, 20)
			y += 30

	# Add OK Button
	#retval += "\n{" + Box("name", "OK") + Box("UI", "Button") + Box("x", str(x)) + Box("y", str(y)) + Box("length", "150") + Box("width", "20", "},")
	retval += AddAttributesUI( "OK", "Button", [], x, y, 100, 20)
	retval += "\n]"
	y += 30
	retval += "\nFormWidth=\"" + str(y) + "\""

	return retval


if __name__ == '__main__':
   #main()
   #print sys.argv
   chk = CheckTDDSyntax( TestCase.Attributes )
   cmd="cmd=\"StateChart\""
   if TestCase.Context == "Part" or TestCase.Context == "Analysis" :
	cmd = "cmd=\"PrtPanel\""

   print cmd
   print AttributesUI(TestCase.Attributes)
   print ProjectUUID(TestCase.Attributes)

   sys.exit(chk.Check())
